package com.xiaolanshu.service.impl;

import com.xiaolanshu.entity.User;
import com.xiaolanshu.exception.BusinessException;
import com.xiaolanshu.service.LoginService;
import com.xiaolanshu.service.UserService;
import com.xiaolanshu.vo.ErrorResult;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //用户登录
    @Override
    public Map<Object, Object> userLogin(Map param) {

        //获取用户名、用户密码、短信验证码
        String username = (String) param.get("username");
        String password = (String) param.get("password");
        String phone = (String) param.get("phone");
        String code = (String) param.get("code");

        //查找用户是否存在
        User user = userService.findUser(username);
        if (user == null) {
            //抛出自定义业务异常
            throw new BusinessException(ErrorResult.userNoExist());
        }
        //判断密码是否正确
        if (!user.getPassword().equals(password)) {
            //抛出自定义业务异常
            throw new BusinessException(ErrorResult.passwordError());
        }

        //从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //抛出自定义业务异常
            throw new BusinessException(ErrorResult.codeError());
        }
        //删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);

        //生成token
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        map.put("password", user.getPassword());

        long now = System.currentTimeMillis();
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, "xiaolanshu") //指定加密算法，加密签名
                .setClaims(map) //写入数据
                .setExpiration(new Date(now + 300000000)) //失效时间
                .compact();

        //将用户信息和token保存在map集合里返回
        Map<Object, Object> re = new HashMap<>();
        re.put("token", token);
        re.put("user", user);

        return re;
    }
}
